layui.use(['form', 'layer', 'laydate', 'table', 'laytpl', "element"], function() {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        element = layui.element,
        table = layui.table;
    var laypage = layui.laypage;

    //新闻列表
    var tableIns = table.render({
        elem: '#newsList',
        url: severUrl + 'get_recruit_data',
        contentType: 'application/json; charset=UTF-8',
        method: 'POST', //方式
        where: { page: 1 },
        cellMinWidth: 95,
        page: false,
        height: "full-125",
        // limit: 7,
        // limits: [10, 15, 20, 25],
        id: "newsListTable",
        cols: [
            [{
                    type: "checkbox",
                    fixed: "left",
                    width: 50
                },
                {
                    field: 'recruit_id',
                    title: '序号',
                    width: 100,
                    align: "center"
                }, {
                    field: 'company',
                    title: '公司名称',
                    width: 120,
                    align: "center"
                },
                {
                    field: 'job_position',
                    title: '招聘职位',
                    width: 150,
                    align: 'center'
                },

                {
                    field: 'title',
                    title: '招聘信息标题',
                    width: 150
                },

                {
                    field: 'look_counts',
                    title: '阅读次数',
                    align: 'center',
                    width: 100
                },
                {
                    field: 'deliver_counts',
                    title: '投递次数',
                    align: 'center',
                    width: 100
                },
                {
                    field: 'status',
                    title: '是否发布',
                    width: 100,
                    align: 'center',
                    templet: function(d) {
                        return '<input type="checkbox" data-id="111" name="status" lay-filter="status" lay-skin="switch" lay-text="发布|撤销" ' + statu(d) + '>'
                    }
                },
                {
                    field: 'create_time',
                    title: '创建时间',
                    align: 'center',
                    minWidth: 100,
                    // templet: function(d) {
                    //     return d.createTime.substring(0, 10);
                    // }
                },
                {
                    field: 'release_time',
                    title: '发布时间',
                    align: 'center',
                    minWidth: 100,
                    templet: function(d) {
                        console.log("发布时间");
                        console.log(d.release_time)
                        return timestampToTime(d.release_time);
                    }
                }, {
                    field: 'region',
                    title: '发布区域',
                    align: 'center',
                    minWidth: 200,
                    // templet: function(d) {
                    //     return d.publishTime.substring(0, 10);
                    // }
                },
                {
                    title: '操作',
                    width: 280,
                    templet: '#newsListBar',
                    fixed: "right",
                    align: "center"
                }
            ]
        ],
        done: function(res, page, count) {
            console.log("ppppp");
            console.log(res);
            console.log(page);
            // console.log(count)
        }
    });
    // 状态
    function statu(status) {
        // console.log("nicia")
        // console.log(status)
        if (status.status == 0) {
            return ""

        } else if (status.status == 1) {
            return "checked"
        }
    }
    console.log("我是玩的");
    console.log(tableIns.config.url)
        // 分页
    $.ajax({
            type: "POST",
            url: severUrl + 'get_recruit_data',
            data: { page: 1 },
            dataType: "json",
            success: function(result) {
                console.log("分页差选")

                console.log(result);
                laypage.render({
                    elem: 'test1',
                    count: result.my_count, //数据总数，从服务端得到
                    curr: 1,
                    jump: function(obj, first) {

                        //首次不执行
                        if (!first) {
                            table.reload("newsListTable", {
                                    where: { page: obj.curr }
                                })
                                //do something
                        }
                    }
                })
            }
        })
        // form.on('switch(newsTop)', function(data){
        //     var index = layer.msg('修改中，请稍候',{icon: 16,time:false,shade:0.8});
        //     setTimeout(function(){
        //         layer.close(index);
        //         if(data.elem.checked){
        //             layer.msg("置顶成功！");
        //         }else{
        //             layer.msg("取消置顶成功！");
        //         }
        //     },500);
        // })

    function timestampToTime(timestamp) {
        var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var D = date.getDate() + ' ';
        var h = date.getHours() + ':';
        var m = date.getMinutes() + ':';
        var s = date.getSeconds();
        return Y + M + D + h + m + s;
    }
    //是否发布
    form.on('switch(status)', function(data) {
        // 获取当前控件         
        var statuStr = '';
        var selectIfKey = data.othis;
        // 获取当前所在行                                                                  
        var parentTr = selectIfKey.parents("tr").find("td").eq(1).text();
        console.log("wokankan");
        console.log(parentTr)
            // console.log(data.elem); //得到checkbox原始DOM对象
        console.log(data.elem.checked); //开关是否开启，true或者false
        if (data.elem.checked == true) {
            statuStr = 1
        } else {
            statuStr = 0

        }
        console.log(statuStr)
            // console.log(data.value); //开关value值，也可以通过data.elem.value得到
            // console.log(data.othis); //得到美化后的DOM对象
            // var that = $(this);
            // console.log(that)
            // console.log("dshffffffj")
            // console.log(data)
        var messages = "";
        var index = layer.msg('修改中，请稍候', {
            icon: 16,
            time: false,
            shade: 0.8
        });
        setTimeout(function() {
            layer.close(index);
            if (data.elem.checked) {
                $.ajax({
                    type: 'POST',
                    url: severUrl + 'change_status', //发送请求  
                    data: {
                        recruit_id: parentTr,
                        status: statuStr
                    },
                    dataType: "json",
                    success: function(result) {
                        console.log(result)
                        layer.msg("发布成功！");

                    }
                })
            } else {
                $.ajax({
                    type: 'POST',
                    url: severUrl + 'change_status', //发送请求  
                    data: {
                        recruit_id: parentTr,
                        status: statuStr
                    },
                    dataType: "json",
                    success: function(result) {
                        console.log(result)
                        layer.msg("发布成功！");

                    }
                })
                layer.msg("撤销成功！");
            }
        }, 500);
    })

    //搜索【此功能需要后台配合，所以暂时没有动态效果示】
    $(".search_btn").on("click", function() {
        if ($(".searchVal").val() != '') {
            table.reload("newsListTable", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    key: $(".searchVal").val() //搜索的关键字
                }
            })
        } else {
            layer.msg("请输入搜索的内容");
        }
    });

    //添加文章

    function addNews(edit) {
        var index = layui.layer.open({
            title: "添加文章",
            type: 2,
            content: "newsAdd.html",
            success: function(layero, index) {
                console.log(layero, index)
                setTimeout(function() {
                    layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 300)
            }
        })
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function() {
            layui.layer.full(index);
        })
    }
    $(".addNews_btn").click(function() {
            addNews();
        })
        //编辑文章
    function editNews(data) {
        var reaigion = data.region.split("-");
        console.log(reaigion[0])
        var index = layui.layer.open({
            title: "修改文章",
            type: 2,
            content: "editNews.html",
            success: function(layero, index) {
                console.log(data);
                console.log("====+success");
                setTimeout(function() {
                    layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 300)
                var body = layui.layer.getChildFrame('body', index);
                console.log("uefhfdhahahacxx");
                body.find(".newsName").eq(2).val(data.title);
                body.find(".newsName").eq(1).val(data.job_position);
                body.find(".newsName").eq(0).val(data.company);

                body.find(".layui-textarea").eq(0).text(data.my_describe);
                body.find(".layui-textarea").eq(1).text(data.my_require);
                body.find("#spans").val(data.recruit_id);
                //				城市地图
                body.find("#inputDiv #providInput").val(reaigion[0]);
                body.find("#inputDiv #cityidInput").val(reaigion[1]);
                body.find("#inputDiv #areaidInput").val(reaigion[2]);
                console.log(body.find("#inputDiv #providInput").val())
            }
        })
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function() {
            layui.layer.full(index);
        })
    }


    //批量删除
    $(".delAll_btn").click(function() {
            var checkStatus = table.checkStatus('newsListTable'),
                data = checkStatus.data,
                id = [];
            console.log(data)
            if (data.length > 0) {
                for (var i in data) {

                    id.push(data[i].recruit_id);
                }
                console.log(id)
                layer.confirm('确定删除选中的文章？', {
                    icon: 3,
                    title: '提示信息'
                }, function(index) {
                    $.post(severUrl + "delete_many_recruit", {
                        recruit_ids: JSON.stringify(id) //将需要删除的newsId作为参数传入
                    }, function(data) {
                        console.log("shanchu")
                        console.log(data)

                    })
                    tableIns.reload();
                    layer.close(index);
                })

            } else {
                layer.msg("请选择需要删除的文章");
            }
        }),


        //列表操作
        table.on('tool(newsList)', function(obj) {
            var layEvent = obj.event,
                data = obj.data;

            if (layEvent === 'edit') { //编辑
                console.log("kkkkkk")
                console.log(data)
                editNews(data);

            } else if (layEvent === 'del') { //删除
                console.log(data)
                layer.confirm('确定删除此文章？', {
                    icon: 3,
                    title: '提示信息'
                }, function(index) {
                    $.post(severUrl + 'delete_recruit_data', {
                        recruit_id: data.recruit_id //将需要删除的newsId作为参数传入
                    }, function(data) {
                        console.log("00000000")
                        console.log(data)
                    })
                    tableIns.reload();
                    layer.close(index);
                });
            } else if (layEvent === 'messageRecord') { //消息记录
                var ii = layer.load();
                //此处用setTimeout演示ajax的回调
                setTimeout(function() {
                    layer.close(ii);
                }, 500);
                var recruitId = data.recruit_id
                console.log(recruitId)
                    // $.ajax({
                    //     type: 'POST',
                    //     url: severUrl + 'get_message_data', //发送请求  
                    //     dataType: "json",
                    //     data: {
                    //         recruitid: recruitId
                    //     },
                    //     success: function(result) {

                //         var htmlCont = result.data; //返回的结果页面  
                //         console.log(htmlCont)
                //         var index = layui.layer.open({
                //             title: '<span class="layui-badge-dot" style="margin-right:10px"></span>' + "消息记录",
                //             type: 2,
                //             area: ['600px', '500px'],
                //             content: 'messageRecord.html',
                //             success: function(layero, index) {
                //                 var body = layui.layer.getChildFrame('body', index);
                //                 var html = '';
                //                 for (var i = 0 in htmlCont) {
                //                     var userId = htmlCont[i].openid;
                //                     var messageContents = htmlCont[i].content;
                //                     var replyTime = htmlCont[i].reply_time;

                //                     html += '<div class="layui-colla-item">' +
                //                         '<h2 class="layui-colla-title"><span class="userName">' + userId + '</span><span style="float:right" class="times">' + userId + '</span></h2>' +
                //                         '<div class="layui-colla-content layui-show messageContent">' +
                //                         '<p>' + messageContents + '</p>' +
                //                         '</div>' +
                //                         '</div>';
                //                 }
                //                 body.find(".layui-collapse").append(html);
                //                 form.render();
                //                 layui.use(['element', 'layer'], function() {
                //                     var element = layui.element;
                //                     var layer = layui.layer;

                //                     //监听折叠
                //                     element.on('collapse(test)', function(data) {
                //                         // layer.msg('展开状态：' + data.show);
                //                     });
                //                 });

                //             }
                //         });
                //     }
                // });

            } else if (layEvent === 'sendRecord') { //投递记录
                console.log("投递记录")
                var ii = layer.load();
                //此处用setTimeout演示ajax的回调
                setTimeout(function() {
                    layer.close(ii);
                }, 300)
                getMessageData(data)

                // $.ajax({
                //     type: 'POST',
                //     url: severUrl + 'get_deliver_by_recruit', //发送请求  
                //     data: {
                //         recruitid: "654321"
                //     },
                //     dataType: "json",
                //     success: function(result) {
                //         console.log("ooooooo");
                //         console.log(result)
                //         var htmlCont = result[0]; //返回的结果页面  
                //         var index = layui.layer.open({
                //             title: '<span class="layui-badge-dot" style="margin-right:10px"></span>' + "投递记录",
                //             type: 2,
                //             area: ['600px', '500px'],
                //             content: 'sendMessage.html',

                //             success: function(layero, index) {
                //                 var body = layui.layer.getChildFrame('body', index);

                //                 console.log(body.find(".userName").text("qianhuah1"));
                //                 var htems = '';
                //                 htems = ' <div class="layui-collapse" lay-filter="test">' +
                //                     '<div class="layui-colla-item">' +
                //                     '<h2 class="layui-colla-title"><span class="layui-badge-dot" style="margin-right:10px"></span><span class="userName">' + htmlCont.openid + '</span><span style="float:right">' + htmlCont.deliver_time + '</span></h2>' +
                //                     '</div>' +
                //                     '</div>';
                //                 body.find(".sendMessage").append(htems);

                //             }
                //         });
                //     }
                // });
            }
        });
    //监听折叠
    element.on('collapse(test)', function(data) {
        //      layer.msg('展开状态：' + data.show);
    });

    // function change() {
    //     console.log("moososjsjjjcnccncn")
    // }


    function jianlidianji() {
        console.log("jjjjjjj")
    }

    // 获取消息
    function getMessageData(data) {
        $.ajax({
            type: 'POST',
            url: severUrl + 'get_deliver_by_recruit', //发送请求  
            data: {
                recruitid: data.recruit_id
            },
            dataType: "json",
            success: function(result) {
                console.log("ooooooo");
                console.log(result)
                if (result.length == 0) {
                    layer.msg("暂无投递记录");
                } else {
                    var htmlCont = result[0]; //返回的结果页面  
                    var index = layui.layer.open({
                        title: '<span style="margin-right:10px"></span>' + "投递记录",
                        type: 2,
                        // area: ['600px', '500px'],
                        content: 'sendMessage.html',

                        success: function(layero, index) {
                            var body = layui.layer.getChildFrame('body', index);
                            var htems = '';
                            console.log("0000");
                            console.log(data);
                            var arr = [];

                            console.log("9999999999999999999")
                            console.log(htmlCont)

                            arr.push(htmlCont);
                            console.log(arr)

                            console.log("---------------------")
                            console.log(htmlCont.openid)
                                // arr.push()

                            // onclick="changes(' + htmlCont.openid + ',' + data.recruit_id + ')"
                            htems = '<div >' +
                                '<h2 class="layui-colla-title"><span class="layui-badge-dot" style="margin-right:10px"></span><span class="userName">投递者:' + htmlCont.openid + '</span><span style="margin-left:10%">投递时间:' + htmlCont.deliver_time + '</span><span id="jianliBtn" class="layui-btn layui-btn-danger addNews_btn" style="margin-left:20%">查看简历</span></h2>' +
                                '<div class="layui-colla-content" style="margin-left:50px">' +
                                // '<p>招聘描述：' + data.my_describe + '</p>' +
                                '</div>' +
                                '</div>'
                                // console.log(body.find(".userName").text("qianhuah1"));
                                // var htems = '';
                                // htems = '<div class="layui-colla-item">' +
                                //     '</div>' +
                                //     '</div>';
                            body.find("#sendMessage").append(htems);



                            body.find("#jianliBtn").click(function() {

                                var openid = htmlCont.openid
                                var recruitId = data.recruit_id

                                $.ajax({
                                    type: 'POST',
                                    url: severUrl + 'get_cv_data_by_openid', //发送请求  
                                    dataType: "json",
                                    data: {
                                        openid: openid
                                    },
                                    success: function(result) {
                                        console.log("jieguo");
                                        // console.log(result.data);
                                        var userInfo = result.data[0];
                                        console.log(userInfo)
                                        layui.layer.open({
                                            title: "预览简历",
                                            type: 2,
                                            area: ["700px", "600px"],
                                            content: '../user/linkList.html',
                                            success: function(layero, index) {
                                                var body = layui.layer.getChildFrame('body', index);
                                                console.log("uefhfdhahahacxx")
                                                body.find(".layui-myinfos h1").text(userInfo.name);
                                                body.find(".jobAge").text(userInfo.job_age)
                                                body.find("#company").text(userInfo.company)
                                                body.find(".myIntroduct").text(userInfo.introduction)
                                                body.find(".job_position").text(userInfo.job_position)
                                                body.find(".tel").text(userInfo.tel);
                                                body.find("#openId").text(userInfo.openid);
                                                body.find("#recruitId").text(recruitId);
                                                body.find(".myImgs").addClass("isblock")

                                            }
                                        });
                                    }
                                })

                            })

                        }
                    });
                    layui.layer.full(index);
                    //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
                    $(window).on("resize", function() {
                        layui.layer.full(index);
                    })
                }

            }

        });

    }

})